'use client'

import React, { useState } from 'react'
import Link from 'next/link'
import { motion, AnimatePresence } from 'framer-motion'
import { usePathname } from 'next/navigation'

export default function HeaderClient({ navigations, className }) {
  const [hovered, setHovered] = useState(null)
  const [hoveredChild, setHoveredChild] = useState(null)
  const pathname = usePathname()

  const activeUrl = hovered || pathname

  return (
    <div className={`naigations h-full flex items-center ${className}`}>
      <ul className="flex h-full items-center justify-between relative">
        {navigations?.header?.map(
          (item) =>
            item.status === 0 && (
              <li key={item.url} className="relative h-full flex items-center transition px-2 lg:px-4" onMouseEnter={() => setHovered(item.url)} onMouseLeave={() => { setHovered(null); setHoveredChild(null) }} >
                <Link href={item.url} className="h-full flex items-center text-md relative" >
                  {item.name}
                  {(activeUrl && (activeUrl === item.url || (item.url !== '/' && activeUrl.startsWith(item.url)))) && (<motion.span layoutId="header-underline" className="absolute bottom-0 left-0 right-0 h-[2px] bg-[var(--theme-color)]" transition={{ type: 'spring', stiffness: 500, damping: 30, }} />)}
                </Link>
                <AnimatePresence>
                  {hovered === item.url && item.children?.length > 0 && (
                    <motion.div initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -10 }} transition={{ duration: 0.15 }} className="absolute top-16 left-1/2 w-60 -translate-x-1/2 bg-white shadow-md rounded-sm overflow-hidden z-50" >
                      <ul className="py-4 px-2 relative">
                        {item.children.map(
                          (child) => child.status === 0 &&
                            (<li key={child.url} className="relative" onMouseEnter={() => setHoveredChild(child.url)} onMouseLeave={() => setHoveredChild(null)} >
                              <Link href={child.url} className="block px-4 py-2 text-sm relative" >
                                {child.name}
                                <motion.span className="absolute bottom-0 left-0 right-0 h-[2px] bg-[var(--theme-color)]" initial={{ scaleX: 0 }} animate={{ scaleX: pathname === child.url || hoveredChild === child.url ? 1 : 0, }} transition={{ duration: 0.3, ease: 'easeInOut', }} style={{ originX: 0 }} />
                              </Link>
                            </li>
                            )
                        )}
                      </ul>
                    </motion.div>
                  )}
                </AnimatePresence>
              </li>
            )
        )}
      </ul>
    </div>
  )
}
